package com.spring.reactive.controller;

import com.spring.reactive.model.User;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@RestController
public class UserController {

    private final List<User> users = new ArrayList<>();

    @PostConstruct
    public void init(){

        users.add(User.builder().id(1).name("jack").address("北京").build());
        users.add(User.builder().id(2).name("rose").address("山东").build());

    }


    @GetMapping
    public Mono<User> get(){
        return Mono.just(users.get(0));
    }

    @GetMapping("all")
    public Mono<List<User>> getAll(){
        return Mono.just(users);
    }

    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Mono<User> add(@RequestBody User user){
        System.out.println(user.toString());
        users.add(user);
        return Mono.just(user);
    }

    @PutMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Mono<User> edit(User user){
        System.out.println(user.toString());
        return Mono.just(user);
    }

    @DeleteMapping("{id}")
    public Mono<User> delete(@PathVariable Integer id){
        AtomicReference<User> res = null;
        users.stream().iterator().forEachRemaining(user->{
            if (user.getId().equals(id)) {
                res.set(user);
                users.remove(user);
                return;
            }
        });
        return Mono.just(res.get());
    }

    @PostMapping(name = "upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Mono<String> upload(@RequestPart MultipartFile file, String fileName) throws IOException {

        file.transferTo(new File("E:\\test.jpg"));

        return Mono.just(fileName);
    }
}
